import fg from "fast-glob"
import fs from "fs"
import path from "path"
import sharp from "sharp"

const assetsDir = path.join(__dirname, "../src/assets/images") // 源目录
const assetsDistDirWebp = path.join(__dirname, "../src/assets/images") // 输出目录（webp）

/**
 * 替换文件扩展名，保持路径结构不变。
 */
function withExt(filePath: string, newExt: string): string {
    const { dir, name } = path.parse(filePath)
    return path.join(dir, `${name}.${newExt.replace(/^\./, "")}`)
}

/**
 * 复制 SVG 文件到目标目录
 */
function copySvgFile(inputPath: string, relativePath: string) {
    const outputPathWebp = path.join(assetsDistDirWebp, relativePath)

    // 确保目标目录存在
    fs.mkdirSync(path.dirname(outputPathWebp), { recursive: true })

    // 复制到 webp 目录
    if (fs.existsSync(outputPathWebp)) {
        console.log(`⏩ SVG 已存在 (webp目录) 跳过复制: ${outputPathWebp}`)
    } else {
        try {
            fs.copyFileSync(inputPath, outputPathWebp)
            console.log(`✅ SVG 复制完成: ${outputPathWebp}`)
        } catch (err) {
            console.error(`❌ SVG 复制失败 (webp目录): ${relativePath}`, err)
        }
    }
}

/**
 * 使用 sharp 压缩图片（webp + avif）
 */
async function compressImage(inputPath: string, relativePath: string) {
    // 如果是 SVG 文件，直接复制不压缩
    if (path.extname(inputPath).toLowerCase() === ".svg") {
        copySvgFile(inputPath, relativePath)
        return
    }

    const outputPathWebp = withExt(path.join(assetsDistDirWebp, relativePath), "webp")

    // 跳过已存在的 .webp
    if (fs.existsSync(outputPathWebp)) {
        console.log(`⏩ 已存在 (webp) 跳过创建压缩: ${outputPathWebp}`)
    } else {
        try {
            fs.mkdirSync(path.dirname(outputPathWebp), { recursive: true })
            const result = await sharp(inputPath).webp({ quality: 75 }).toFile(outputPathWebp)
            console.log(`✅ 压缩完成: WEBP 源文件 ${relativePath} (${result.size} bytes)`)
        } catch (err) {
            console.log(`❌ 创建目录失败: ${outputPathWebp}`)
        }
    }
}

/**
 * 主流程
 */
async function main() {
    console.log("🔍 正在扫描资源目录...")

    const waitCompressList = await fg("**/*.{jpg,jpeg,png,svg}", {
        cwd: assetsDir,
    })

    console.log(`📦 共找到 ${waitCompressList.length} 张图片\n`)

    for (const relativePath of waitCompressList) {
        const inputPath = path.join(assetsDir, relativePath)
        await compressImage(inputPath, relativePath)
    }

    console.log("\n🎉 所有图片处理完成！")
}

main()
